import { Module } from "vuex";
import { ILoginState, IRooteState } from "../types";
import { accountLogin, reqUserInfo, reqUserMenu } from "@/service/login/login";
import store from "@/utils/storage";
import router from "@/router";
import { mapMenuToRoutes } from "@/utils/mapMenus";
const loginModule: Module<ILoginState, IRooteState> = {
  // 如果想 使用 store.dispatch("login/accountLoginAction", { ...account })的形式派发模块action必须使用 namespaced: true 命名空间
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: {},
      userMenus: [],
      headerTitle: "",
    };
  },
  actions: {
    //   发送请求的action为异步action
    async accountLoginAction({ commit }, payload: any) {
      // 请求用户token 缓存本地  并且保存在vuex中
      const loginRes: any = await accountLogin(payload);
      const { id, token } = loginRes.data;
      //   缓存token以便于每次发送请求都可以携带token
      store.setStorage("token", token);
      commit("changeToken", token);
      //   请求用户信息 并且缓存
      const userInfoRes: any = await reqUserInfo(id);
      const userInfo = userInfoRes.data;
      store.setStorage("userInfo", userInfo);
      commit("changeUserInfo", userInfo);
      //   请求登陆用户可展示的菜单
      const userMenusRes: any = await reqUserMenu(userInfo.role.id);
      const userMenus = userMenusRes.data;
      commit("changeUserMenus", userMenus);
      store.setStorage("userMenus", userMenus);
      // 登陆完成后跳转到首页
      router.push("/main");
    },
    loadLocalLoginData({ commit }) {
      // 在main.ts中一进入就会查找缓存中是否存在用户信息 如果存在则存入vuex中
      // 防止用户直接进入main页面 或者刷新页面 vuex中的数据丢失的情况
      const token = store.getStorage("token");
      if (token) {
        commit("changeToken", token);
      }

      const userInfo = store.getStorage("userInfo");
      if (userInfo) {
        commit("changeUserInfo", userInfo);
      }
      const userMenus = store.getStorage("userMenus");
      if (userMenus) {
        commit("changeUserMenus", userMenus);
      }
    },
  },
  mutations: {
    changeToken(state, payload) {
      state.token = payload;
    },
    changeUserInfo(state, payload) {
      state.userInfo = payload;
    },
    changeUserMenus(state, payload) {
      state.userMenus = payload;
      const userMenus = store.getStorage("userMenus");
      const routes = mapMenuToRoutes(userMenus);
      // 将映射菜单后的路由添加到main的子路由中
      routes.forEach((route) => {
        router.addRoute("main", route);
      });
    },
    changeHeaderTitle(state, payload) {
      state.headerTitle = payload;
    },
  },
  getters: {},
};

export default loginModule;
